//
//  OCSSOverBookingPage.swift
//  OCSSStoreSwift
//
//  Created by MacMiniKangChe on 2018/10/11.
//  Copyright © 2018年 MacMiniKangChe. All rights reserved.
//

import UIKit
import SwiftyJSON
import HandyJSON

enum BookOrderType:Int {
    case retail = -2  //零售下单
    case purches = -1 //申请采购
    case allot = 0  //申请调拨
    case distribution = 1 //申请铺货
}

class OCSSOverBookingPage: OCSSBaseRefreshViewController,UITableViewDelegate, UITableViewDataSource, OCSSOverBookCellDelegate {
    
    var type:BookOrderType?=BookOrderType.retail;
    

    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var headerViewHeight: NSLayoutConstraint!
    @IBOutlet weak var locationView: UIView!
    
    var orderData:NSMutableArray?;
    var selectRows:NSMutableDictionary?;

    var isHasLocation:Bool = false;

    override func viewDidLoad() {
        super.viewDidLoad()
        
        config();
        if isHasLocation{
            locationView.isHidden = false;
            headerViewHeight.constant = 122;
        }else{
            locationView.isHidden = true;
            headerViewHeight.constant = 70;
        }
        requestForOrderData();
    }
    func config() -> Void {
        //自定义UISearchbar的样式
        for view in (searchBar.subviews.first?.subviews)! {
            if view.isKind(of: UITextField.classForCoder()){
                let textField = view as! UITextField;
                textField.backgroundColor = UIColor.colorWithHex(colorStr: "edf4fb");
                textField.background = nil;
                textField.borderStyle = UITextBorderStyle.none;
                textField.layer.cornerRadius = 4;
                textField.clipsToBounds = true;
                print(textField);
                print(searchBar);
            }
        }
        orderData = NSMutableArray.init();
        selectRows = NSMutableDictionary.init();
        locationView.subviews.first?.layer.cornerRadius = 4;
        locationView.subviews.first?.clipsToBounds = true;
        bottomView.layer.borderColor = UIColor.init(red: 249.0/255.0, green: 249.0/255.0, blue: 249.0/255.0, alpha: 1).cgColor;
        self.regTableViewNib(tableView: tableView, className: OCSSOverBookCell.className());
        tableView.tableFooterView = UIView();
    }
    //MARK:ButtonEvent
    @IBAction func addressButtonEvent(_ sender: UIButton) {
        let addressView:UIView = OCSSAddressSelectView.init(frame: CGRect.init(x: 0, y: 0, width: kWidth, height: 375));
        MYBottomPopView.showWithContentView(contentView: addressView);
    }
    @IBAction func sureButtonEvent(_ sender: UIButton) {
        let selectCars = getSelectCars(arr: self.orderData as! [OCSSOverBookModel])
        if (selectCars.count == 0) {
            return;
        }
        let submitVC = OCSSWriteOrderInfoPage.init();
        submitVC.selectCars = (getSelectCars(arr: self.orderData as! [OCSSOverBookModel]) as! [OCSSOverBookModel]);
        submitVC.hidesBottomBarWhenPushed = true;
        navigationController?.pushViewController(submitVC, animated: true);
    }
//    请求订单数据
    func requestForOrderData() -> Void {
        let pageIndex = String(page);
        var url = "";
        var paras:[String:String]?=[:];
        switch type {
        case .retail?:
            url = "/PlaceOrder/Query_app";
            paras = ["pageIndex":pageIndex,
                     "Key":""];
            break;
        case .purches?:
            url = "/StoreHouse/ApplyPurchasingProduct_app";
            break;
        case .allot? ,.distribution?:
            url = "/StoreHouse/Query_app";
            paras = (["pageIndex":pageIndex,
                      "Key":"",
                      "IsO2O":String(format: "%d", (type?.rawValue)!),
                      "AreaCode":"0"] );
            break;
        default: break
            
        }
        
        OCSSNetRequest.requestData(url: url, para: paras!, type: MethodType.post, success: { (result) in
            let resDic = JSON(result).dictionaryObject;
            if (JSON(resDic!["Status"] as Any).boolValue){
                let arr = JSON(resDic!["Data"]!).arrayObject as! [[String:Any]];
                let datas = [OCSSOverBookModel].deserialize(from: arr);
                if ((datas?.count) != 0 && self.page != 1) {
                    self.orderData?.addObjects(from: self.dealWithData(arr: datas as! [OCSSOverBookModel]));
                }
                if datas?.count != 0 && self.page == 1{
                    self.orderData?.removeAllObjects();
                    self.orderData?.addObjects(from: self.dealWithData(arr: self.dealWithData(arr: datas! as! [OCSSOverBookModel])));
                }
                self.tableView.reloadData();
            }

        }) { (error) in
            print("reuqest error :\(error)");
        }
    }
    //MARK:处理数据
    func dealWithData(arr:[OCSSOverBookModel]) -> [OCSSOverBookModel] {
        let models = NSMutableArray.init();
        for index in 0...arr.count-1 {
            let model = arr[index] as OCSSOverBookModel;
            for key in (selectRows?.allKeys)!{
                if Int(model.ID) == (key as! Int){
                    model.Quantity = selectRows![key] as! Int;
                }
            }
            models.add(model);
            
        }
        return models as! [OCSSOverBookModel];
    }
    func getSelectCars(arr:[OCSSOverBookModel]) -> NSArray {
        let array = NSMutableArray.init();
        for model in arr {
            if model.Quantity != 0 {
                array.add(model);
            }
        }
        return array;
    }
    //下拉刷新
    override func refresh() {
        page = 1;
        requestForOrderData();
    }
    //上拉加载更多
    override func loadMore() {
        page += 1;
        requestForOrderData();
    }
    //MARK:TableViewDelegate && UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (orderData?.count)!;
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:OCSSOverBookCell = tableView.dequeueReusableCell(withIdentifier: String(describing: OCSSOverBookCell.classForCoder())) as! OCSSOverBookCell;
        cell.selectionStyle = UITableViewCellSelectionStyle.none;
        cell.delegate = self;
        cell.model = self.orderData?[indexPath.row] as? OCSSOverBookModel;
        
        return cell;
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100;
    }
    //MARK:OCSSOverBookCellDelegate
    func addButtonDidClicked(button: UIButton, count: NSInteger, cell: OCSSOverBookCell,model:OCSSOverBookModel) {
        let indexPath = tableView.indexPath(for: cell);
        let key = model.ID;
        model.Quantity = count;
        selectRows?.setValue(count, forKey: key!);
        tableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.automatic);
    }
    func decButtonDidClicked(button: UIButton, count: NSInteger, cell: OCSSOverBookCell,model:OCSSOverBookModel) {
        let indexPath = tableView.indexPath(for: cell);
        let key = model.ID;
        model.Quantity = count;
        selectRows?.setValue(count, forKey: key!);
        tableView.reloadRows(at: [indexPath!], with: UITableViewRowAnimation.automatic);
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
